<template>
  <div>
    <div class="page-title">销售管理</div>
    
    <div class="card-container">
      <div class="search-form">
        <el-form :inline="true" :model="searchForm">
          <el-form-item label="产品名称">
            <el-input v-model="searchForm.productName" placeholder="请输入产品名称" />
          </el-form-item>
          <el-form-item label="会员姓名">
            <el-input v-model="searchForm.memberName" placeholder="请输入会员姓名" />
          </el-form-item>
          <el-form-item label="支付方式" style="width: 200px;">
            <el-select v-model="searchForm.paymentMethod" placeholder="请选择支付方式" clearable>
              <el-option label="现金" value="BALANCE" />
              <el-option label="微信" value="WECHAT" />
              <el-option label="支付宝" value="ALIPAY" />
            </el-select>
          </el-form-item>
          <el-form-item label="日期范围">
            <el-date-picker
              v-model="searchForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              style="width: 240px"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <div class="table-operations">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新增销售
        </el-button>
      </div>
      
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="productName" label="产品名称" />
        <el-table-column prop="memberName" label="会员姓名" />
        <el-table-column prop="quantity" label="数量" width="80" />
        <el-table-column prop="unitPrice" label="单价" width="100">
          <template #default="{ row }">
            ¥{{ row.unitPrice }}
          </template>
        </el-table-column>
        <el-table-column prop="totalAmount" label="总金额" width="100">
          <template #default="{ row }">
            ¥{{ row.totalAmount }}
          </template>
        </el-table-column>
        <el-table-column prop="paymentMethod" label="支付方式" width="100">
          <template #default="{ row }">
            {{ getPaymentMethodText(row.paymentMethod) }}
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="销售时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" text @click="handleView(row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { SaleRecord } from '@/types'
import { getSales, createSale, deleteSale } from '@/api/sales'

const searchForm = reactive({
  productName: '',
  memberName: '',
  paymentMethod: '',
  dateRange: []
})

const tableData = ref<SaleRecord[]>([])
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0
})

const loadData = async () => {
  try {
    const params = {
      ...searchForm,
      current: pagination.current,
      size: pagination.pageSize
    }
    const { records, total } = await getSales(params)
    tableData.value = records
    pagination.total = total
  } catch (error) {
    console.error('加载数据失败:', error)
  }
}

const handleSearch = () => {
  pagination.current = 1
  loadData()
}

const handleReset = () => {
  searchForm.productName = ''
  searchForm.memberName = ''
  searchForm.paymentMethod = ''
  searchForm.dateRange = []
  handleSearch()
}

const handleSizeChange = (val: number) => {
  pagination.pageSize = val
  loadData()
}

const handleCurrentChange = (val: number) => {
  pagination.current = val
  loadData()
}

const handleAdd = () => {
  // 跳转到新增销售页面
}

const handleView = (row: SaleRecord) => {
  // 查看销售详情
}

const handleDelete = async (row: SaleRecord) => {
  try {
    await ElMessageBox.confirm('确定要删除该销售记录吗？', '提示', {
      type: 'warning'
    })
    await deleteSale(row.id)
    ElMessage.success('删除成功')
    loadData()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
    }
  }
}

const getPaymentMethodText = (method: string) => {
  const map: Record<string, string> = {
    BALANCE: '余额',
    WECHAT: '微信',
    ALIPAY: '支付宝'
  }
  return map[method] || method
}

const formatDate = (date: string) => {
  return new Date(date).toLocaleString()
}

onMounted(() => {
  loadData()
})
</script>